package review.config;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import review.entity.Users;
import review.entity.model.UserState;
import review.system.service.UserService;

public class MyRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		Users user = (Users) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		List<String> roles = userService.findRolesByUserid(user.getId());
		for (String role : roles) {
			info.addRole(role);
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		if (request.getMethod().equalsIgnoreCase("get")) {
			return null;
		}
		UsernamePasswordToken t1 = (UsernamePasswordToken) token;
		Users user = userService.findUserByLoginname(t1.getUsername());
		if (user == null) {
			throw new UserNotFoundException();
		}
		if (user.getState() == UserState.DISABLE.getValue()) {
			throw new UserForbiddenException();
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
	}

}
